<?php
/**
 * Created by PhpStorm.
 * User: mww
 * Remark: 网盘专用
 */
namespace app\api\controller;
use think\Db;
class Myinfo extends Base
{
    /**
     * 异地登录验证
     * @return string|void
     */
    public function _initialize()
    {
        extract(input());
        if($user_id != 0){
            $auth = $this->checkAll($user_id,$time,$value,$reqKey);
            if($auth == 112){
                echo json_encode(['status'=>301,'msg'=>$this->otherLogin]);
                exit;
            }elseif($auth == 110){
                echo json_encode(['status' => 302, 'msg' => $this->frost]);
                exit;
            }elseif($auth == 1103){
                echo json_encode(['status' => 303, 'msg' => $this->del]);
                exit;
            }
        }

    }


    /**
     * 我的网盘汇总信息
     */
    public function myYun()
    {
        extract(input());
        $user = $this->getUserInfo($user_id,'user_id,user_username,user_image,user_ram,user_ram_use',2);
        return json(['status'=>200,'msg'=>$user]);
    }
    /**
     * 我的网盘数据——最外层
     */
    public function myYunData()
    {
        extract(input());
        $where['uy_user_id'] = $user_id;
        $where['uy_status'] = 1;
        if(isset($keyword) && $keyword){
            $where['uy_name'] = ['like','%'.$keyword.'%'];
        }else{
            $where['uy_fid'] = 0;
        }
        //复制移动获取第一层
        if(isset($copy_move) && $copy_move){
            $where['uy_type'] = 1;
        }
        //复制移动获取第一层
        $data = Db::table('up_user_yun')
            ->where($where)
            ->order('uy_type asc,uy_time desc')
            ->page($page,20)
            ->select();
        return json(['status'=>200,'msg'=>$data]);
    }
    /**
     * 回收站
     */
    public function recycleData()
    {
        extract(input());
        $where['uy_user_id'] = $user_id;
        $where['uy_status'] = 2;
        $data = Db::table('up_user_yun')
            ->where($where)
            ->order('uy_type asc,uy_time desc')
            ->page($page,20)
            ->select();
        return json(['status'=>200,'msg'=>$data]);
    }
    /**
     * 我的网盘数据——某文件夹下
     */
    public function myYunSonData()
    {
        extract(input());
        $where['uy_fid'] = $uy_id;
        $where['uy_status'] = 1;
        //复制移动获取某文件夹下文件夹
        if(isset($copy_move) && $copy_move){
            $where['uy_type'] = 1;
        }
        //复制移动获取某文件夹下文件夹
        $data = Db::table('up_user_yun')
            ->where($where)
            ->order('uy_type asc,uy_time desc')
            ->page($page,20)
            ->select();
        return json(['status'=>200,'msg'=>$data]);
    }
    /**
     * 新建
     */
    public function addFile()
    {
        extract(input());
        $today = date('Y-m-d H:i:s');
        $user = $this->getUserInfo($user_id,'user_ram,user_ram_use',2);
        $can = $user['user_ram'] - $user['user_ram_use'];
        if($type > 1 && $can < $size){
            return json(['status'=>0,'msg'=>'内存不足']);
        }
        $add = [
            'uy_user_id' => $user_id,
            'uy_fid' => $uy_id,
            'uy_type' => $type,
            'uy_name' => $name,
            'uy_url' => $url, //文件夹类型为空
            'uy_size' => $size,//文件夹类型为0
            'uy_time' => $today,
            'uy_update' => $today,
        ];
        Db::startTrans();
        try {
            $id = Db::table('up_user_yun')->insertGetId($add);
            if($uy_id == 0 || !$uy_id){
                $id_str = ','.$id.',';
            }else{
                $fstr = Db::table('up_user_yun')->where('uy_id',$uy_id)->value('uy_id_str');
                $id_str = $fstr . $id . ',';
            }
            Db::table('up_user_yun')->where('uy_id',$id)->setField('uy_id_str',$id_str);
            if($size > 0){
                Db::table('up_u_user')->where('user_id',$user_id)->setInc('user_ram_use',$size);
            }
            Db::commit();
            return json(['status'=>200,'msg'=>'新建成功']);
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return json(['status'=>0,'msg'=>'新建失败，请刷新测试']);
        }
    }

    /**
     * 复制或移动
     * 从聊天处保存到自己的网盘传复制类型即可
     * type：1复制  2移动
     * fid：目标id
     * @return \think\response\Json
     */
    public function fileCopyMove()
    {
        extract(input());
        if($fid > 0 && $fid){
            $fstatus = Db::table('up_user_yun')->where('uy_id',$fid)->value('uy_status');
            if($fstatus != 1){
                return json(['status'=>0,'msg'=>'目标文件夹不存在，请重新选择']);
            }
        }
        //--------------------不能复制或移动到自身或子目录下 start -------------------------
        $no_1 = Db::table('up_user_yun')
            ->where('uy_id', 'in',$ids)
            ->where('uy_type', 1)
            ->field('uy_id_str')
            ->select();
        if($no_1){
            $no_2 = Db::table('up_user_yun')->where('uy_id',$fid)->value('uy_id_str');
            foreach ($no_1 as $nok => $nov){
                if(strstr($no_2,$nov['uy_id_str'])){
                    return json(['status'=>0,'msg'=>'不能复制或移动到自身或子目录下']);
                }
            }
        }
        //--------------------不能复制或移动到自身或子目录下 end ------------------------
        $ids = explode(',',$ids);
        $user = $this->getUserInfo($user_id,'user_ram,user_ram_use',2);
        $can = $user['user_ram'] - $user['user_ram_use'];
        $allsize = 0;
        //----------------------------------------------------------------
        if($type == 1) {
            foreach ($ids as $kk => $vv) {
                //先判断复制的情况下内存够不够
                $uy_id = $vv;
                $self = Db::table('up_user_yun')->where('uy_id', $uy_id)->find();
                if ($self['uy_type'] == 1) {
                    $size = Db::table('up_user_yun')
                        ->where('uy_status', 1)
                        ->where('uy_id_str', 'like', '%' . $self['uy_id_str'] . '%')
                        ->sum('uy_size');
                } else {
                    $size = $self['uy_size'];
                }
                $allsize += $size;
            }
            if($can < $allsize){
                return json(['status'=>0,'msg'=>'内存不足']);
            }
            if($allsize > 0){
                Db::table('up_u_user')->where('user_id',$user_id)->setInc('user_ram_use',$allsize);
            }
        }
        //----------------------------------------------------------------
        foreach ($ids as $kk => $vv){
            //先判断复制的情况下内存够不够
            $uy_id = $vv;
            $self = Db::table('up_user_yun')->where('uy_id',$uy_id)->find();
            //开始复制移动
            $self['uy_fid'] = $fid;
            $self['uy_user_id'] = $user_id;
            unset($self['uy_id']);
            //先插入拿到id，再改掉复制的这个文件的idstr
            $newid = Db::table('up_user_yun')->insertGetId($self);
            if($fid > 0 && $fid){
                $fstr = Db::table('up_user_yun')->where('uy_id',$fid)->value('uy_id_str');
                $id_str = $fstr . $newid . ',';
            }else{
                $id_str = ',' . $newid . ',';
            }
            Db::table('up_user_yun')->where('uy_id',$newid)->setField('uy_id_str',$id_str);
            if($self['uy_type'] == 1){
                $this->digui($uy_id,$newid,$user_id);
            }
            if($type == 2){
                Db::table('up_user_yun')
                    ->where('uy_status',1)
                    ->where('uy_id_str','like','%'.$self['uy_id_str'].'%')
                    ->delete();
            }
        }
        return json(['status'=>200,'msg'=>'操作成功']);
    }
    public function digui($uy_id,$newid,$user_id) //源文件夹id，目标文件夹id
    {
        //用fid的方式查，如果这个文件夹被冻结了，则此文件夹下的所有内容都不会被查出来，自带矫正
        //但是上面的用的是like的方式，会把下面的查出来，所以加了个status为3的情况，这样可以防止计算错误，在删除时别忘了3的情况
        //删除的时候不考虑特殊性，全删
        $self = Db::table('up_user_yun')
            ->where('uy_status',1)
            ->where('uy_fid',$uy_id)
            ->select();
        if($self){
            foreach ($self as $k => $v){
                //开始复制
                $oid = $v['uy_id'];
                $v['uy_fid'] = $newid;
                $v['uy_user_id'] = $user_id;
                unset($v['uy_id']);
                //先插入拿到id，再改掉复制的这个文件的idstr
                $newid2 = Db::table('up_user_yun')->insertGetId($v);
                $fstr = Db::table('up_user_yun')->where('uy_id',$newid)->value('uy_id_str');
                $id_str = $fstr . $newid2 . ',';
                Db::table('up_user_yun')->where('uy_id',$newid2)->setField('uy_id_str',$id_str);
                if($v['uy_type'] == 1){
                    $this->digui($oid,$newid2,$user_id);
                }
            }
        }
        return true;
    }
    /**
     * 加入回收站
     * @return \think\response\Json
     */
    public function delFake()
    {
        extract(input());
        Db::startTrans();
        try {
            Db::table('up_user_yun')
                ->where('uy_id','in',$ids)
                ->setField('uy_status',2);
            $data = Db::table('up_user_yun')
                ->where('uy_id','in',$ids)
                ->select();
            foreach ($data as $k => $v){
                $have = Db::table('up_user_yun')
                    ->where('uy_status',1)
                    ->where('uy_id','<>',$v['uy_id'])
                    ->where('uy_id_str','like','%'.$v['uy_id_str'].'%')
                    ->find();
                if($have){
                    Db::table('up_user_yun')
                        ->where('uy_status',1)
                        ->where('uy_id','<>',$v['uy_id'])
                        ->where('uy_id_str','like','%'.$v['uy_id_str'].'%')
                        ->setField('uy_status',3);
                }
            }
            Db::commit();
            return json(['status'=>200,'msg'=>'操作成功']);
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return json(['status'=>0,'msg'=>'操作失败，请刷新测试']);
        }
    }
    /**
     * 删除
     * @return \think\response\Json
     */
    public function delReal()
    {
        extract(input());
        Db::startTrans();
        try {
            $allsize = 0;
            $data = Db::table('up_user_yun')
                ->where('uy_id','in',$ids)
                ->select();
            foreach ($data as $k => $v){
                $have = Db::table('up_user_yun')
                    ->where('uy_id_str','like','%'.$v['uy_id_str'].'%')
                    ->find();
                if($have){
                    $size = Db::table('up_user_yun')
                        ->where('uy_id_str','like','%'.$v['uy_id_str'].'%')
                        ->sum('uy_size');
                    $allsize += $size;
                    Db::table('up_user_yun')
                        ->where('uy_id_str','like','%'.$v['uy_id_str'].'%')
                        ->delete();
                }
            }
            if($allsize > 0){
                Db::table('up_u_user')->where('user_id',$user_id)->setDec('user_ram_use',$allsize);
            }
            Db::commit();
            return json(['status'=>200,'msg'=>'操作成功']);
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return json(['status'=>0,'msg'=>'操作失败，请刷新测试']);
        }
    }
    /**
     * 恢复还原
     *
     * @return \think\response\Json
     */
    public function dataBack()
    {
        extract(input());
        Db::startTrans();
        try {
            $ids = explode(',',trim($ids,','));
            $data = Db::table('up_user_yun')
                ->where('uy_id','in',$ids)
                ->select();
            foreach ($data as $k => $v){
                if($v['uy_fid'] == 0){
                    Db::table('up_user_yun')
                        ->where('uy_id_str','like','%'.$v['uy_id_str'].'%')
                        ->setField('uy_status',1);
                }else{
                    //先不管上下级什么的，先该再说
                    $have = Db::table('up_user_yun')
                        ->where('uy_status','in','2,3')
                        ->where('uy_id_str','like','%'.$v['uy_id_str'].'%')
                        ->find();
                    if($have){
                        Db::table('up_user_yun')
                            ->where('uy_status','in','2,3')
                            ->where('uy_id_str','like','%'.$v['uy_id_str'].'%')
                            ->setField('uy_status',1);
                    }
                    //在考虑数据正确性的问题（防止被删掉）
                    $have2 = Db::table('up_user_yun')
                        ->where('uy_status',1)
                        ->where('uy_id',$v['uy_fid'])
                        ->find();
                    if(!$have2){
                        //先把这个的父id改为0，放到最上面去
                        Db::table('up_user_yun')->where('uy_id',$v['uy_id'])->setField('uy_fid',0);
                        //把包含自己的已经正常的数据拿出来，重新赋值str
                        $last = Db::table('up_user_yun')
                            ->where('uy_status',1)
                            ->where('uy_id_str','like','%'.$v['uy_id_str'].'%')
                            ->select();
                        $idstr = $v['uy_id_str'];
                        $index = stripos($idstr,','.$v['uy_id'].',');
                        $no = substr($idstr,0,$index+1); //这是要去掉的一截
                        foreach ($last as $kkk => $vvv){
                            $newstr = str_replace($no,',',$vvv['uy_id_str']);
                            Db::table('up_user_yun')->where('uy_id',$vvv['uy_id'])->setField('uy_id_str',$newstr);
                        }
                    }
                }
            }
            Db::commit();
            return json(['status'=>200,'msg'=>'操作成功']);
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return json(['status'=>0,'msg'=>'操作失败，请刷新测试']);
        }
    }
    /**
     * 重命名
     * @return \think\response\Json
     */
    public function updateName()
    {
        extract(input());
        $update = [
            'uy_name' => $name,
            'uy_update' => date('Y-m-d H:i:s')
        ];
        $res = Db::table('up_user_yun')
            ->where('uy_id',$uy_id)
            ->update($update);
        if($res){
            return json(['status'=>200,'msg'=>'操作成功']);
        }else{
            return json(['status'=>100,'msg'=>'操作失败，请刷新重试']);
        }

    }
}